<template>
  <div id="app">
    <el-container>
      <el-header>
        <h1>用户管理系统</h1>
        <p>演示共享组件 Customer.vue 的使用</p>
      </el-header>
      
      <el-main>
        <el-row>
          <el-col :span="24">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>客户列表</span>
                  <el-button type="primary" @click="handleAddCustomer">
                    <el-icon><Plus /></el-icon>
                    添加客户
                  </el-button>
                </div>
              </template>

              <!-- 搜索区域 -->
              <div class="search-section">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索客户姓名或邮箱"
                  style="width: 300px; margin-right: 16px;"
                  clearable
                  @input="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                
                <el-select
                  v-model="statusFilter"
                  placeholder="筛选状态"
                  style="width: 120px;"
                  clearable
                  @change="handleStatusFilter"
                >
                  <el-option label="活跃" value="active" />
                  <el-option label="非活跃" value="inactive" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="已封禁" value="blocked" />
                </el-select>
              </div>

              <!-- 客户列表 -->
              <div class="customer-list">
                <el-row :gutter="16">
                  <el-col 
                    v-for="customer in filteredCustomers" 
                    :key="customer.id" 
                    :span="8"
                  >
                    <Customer
                      :customer="customer"
                      @view="handleViewCustomer"
                      @edit="handleEditCustomer"
                      @delete="handleDeleteCustomer"
                    >
                      <!-- 扩展信息插槽 -->
                      <template #extra="{ customer }">
                        <el-row :gutter="8">
                          <el-col :span="12">
                            <el-statistic title="订单数量" :value="customer.orderCount || 0" />
                          </el-col>
                          <el-col :span="12">
                            <el-statistic 
                              title="消费金额" 
                              :value="customer.totalAmount || 0" 
                              prefix="¥"
                              :precision="2"
                            />
                          </el-col>
                        </el-row>
                      </template>

                      <!-- 自定义操作按钮 -->
                      <template #actions="{ customer }">
                        <el-button size="small" @click="handleViewCustomer(customer)">
                          <el-icon><View /></el-icon>
                          查看
                        </el-button>
                        <el-button 
                          size="small" 
                          type="primary" 
                          @click="handleEditCustomer(customer)"
                        >
                          <el-icon><Edit /></el-icon>
                          编辑
                        </el-button>
                        <el-dropdown @command="(command) => handleMoreActions(command, customer)">
                          <el-button size="small">
                            更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item command="reset-password">
                                <el-icon><Key /></el-icon>
                                重置密码
                              </el-dropdown-item>
                              <el-dropdown-item command="send-message">
                                <el-icon><ChatDotRound /></el-icon>
                                发送消息
                              </el-dropdown-item>
                              <el-dropdown-item 
                                command="toggle-status"
                                :divided="true"
                              >
                                <el-icon><Switch /></el-icon>
                                {{ customer.status === 'active' ? '禁用' : '启用' }}
                              </el-dropdown-item>
                              <el-dropdown-item command="delete" class="danger-item">
                                <el-icon><Delete /></el-icon>
                                删除
                              </el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </template>
                    </Customer>
                  </el-col>
                </el-row>
              </div>

              <!-- 空状态 -->
              <el-empty v-if="filteredCustomers.length === 0" description="暂无客户数据" />
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 客户详情对话框 -->
    <el-dialog v-model="dialogVisible" title="客户详情" width="600px">
      <div v-if="selectedCustomer">
        <Customer 
          :customer="selectedCustomer" 
          :show-actions="false"
        >
          <template #extra="{ customer }">
            <el-descriptions title="详细信息" :column="2" border>
              <el-descriptions-item label="最后登录">
                {{ formatDate(customer.lastLoginTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="注册IP">
                {{ customer.registerIp || '未知' }}
              </el-descriptions-item>
              <el-descriptions-item label="地区">
                {{ customer.region || '未知' }}
              </el-descriptions-item>
              <el-descriptions-item label="来源">
                {{ customer.source || '直接注册' }}
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </Customer>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEditCustomer(selectedCustomer)">
          编辑客户
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  View, 
  Edit, 
  ArrowDown, 
  Key, 
  ChatDotRound, 
  Switch, 
  Delete 
} from '@element-plus/icons-vue'

// 导入共享组件和工具
import { Customer } from '@admin/shared-components'
import { formatDate, debounce, customerApi } from '@admin/shared-utils'

export default {
  name: 'App',
  components: {
    Customer,
    Plus,
    Search,
    View,
    Edit,
    ArrowDown,
    Key,
    ChatDotRound,
    Switch,
    Delete
  },
  setup() {
    const customers = ref([])
    const searchKeyword = ref('')
    const statusFilter = ref('')
    const dialogVisible = ref(false)
    const selectedCustomer = ref(null)

    // 模拟客户数据
    const mockCustomers = [
      {
        id: 'CU001',
        name: '张三',
        email: 'zhangsan@example.com',
        phone: '13800138001',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        status: 'active',
        createTime: '2023-01-15T10:30:00',
        lastLoginTime: '2024-01-20T15:45:00',
        orderCount: 25,
        totalAmount: 12580.50,
        registerIp: '192.168.1.100',
        region: '北京市朝阳区',
        source: '微信推广'
      },
      {
        id: 'CU002',
        name: '李四',
        email: 'lisi@example.com',
        phone: '13800138002',
        status: 'inactive',
        createTime: '2023-02-20T14:20:00',
        lastLoginTime: '2023-12-25T09:15:00',
        orderCount: 8,
        totalAmount: 3250.00,
        registerIp: '192.168.1.101',
        region: '上海市浦东新区',
        source: '直接注册'
      },
      {
        id: 'CU003',
        name: '王五',
        email: 'wangwu@example.com',
        phone: '13800138003',
        status: 'pending',
        createTime: '2024-01-10T16:45:00',
        orderCount: 0,
        totalAmount: 0,
        registerIp: '192.168.1.102',
        region: '广州市天河区',
        source: 'SEO'
      },
      {
        id: 'CU004',
        name: '赵六',
        email: 'zhaoliu@example.com',
        phone: '13800138004',
        status: 'blocked',
        createTime: '2023-08-05T11:30:00',
        lastLoginTime: '2023-11-15T20:30:00',
        orderCount: 156,
        totalAmount: 45620.80,
        registerIp: '192.168.1.103',
        region: '深圳市南山区',
        source: '朋友推荐'
      }
    ]

    // 筛选后的客户列表
    const filteredCustomers = computed(() => {
      let result = customers.value

      // 按关键词筛选
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(customer => 
          customer.name.toLowerCase().includes(keyword) ||
          customer.email.toLowerCase().includes(keyword)
        )
      }

      // 按状态筛选
      if (statusFilter.value) {
        result = result.filter(customer => customer.status === statusFilter.value)
      }

      return result
    })

    // 防抖搜索
    const handleSearch = debounce((value) => {
      console.log('搜索:', value)
    }, 300)

    // 状态筛选
    const handleStatusFilter = (value) => {
      console.log('状态筛选:', value)
    }

    // 事件处理函数
    const handleAddCustomer = () => {
      ElMessage.info('打开添加客户对话框')
    }

    const handleViewCustomer = (customer) => {
      selectedCustomer.value = customer
      dialogVisible.value = true
    }

    const handleEditCustomer = (customer) => {
      ElMessage.info(`编辑客户: ${customer.name}`)
      // 这里可以打开编辑对话框
    }

    const handleDeleteCustomer = (customer) => {
      // Customer组件内部已经处理了确认对话框
      const index = customers.value.findIndex(c => c.id === customer.id)
      if (index > -1) {
        customers.value.splice(index, 1)
        ElMessage.success(`客户 ${customer.name} 已删除`)
      }
    }

    const handleMoreActions = async (command, customer) => {
      switch (command) {
        case 'reset-password':
          try {
            await ElMessageBox.confirm(
              `确定要重置客户 "${customer.name}" 的密码吗？`,
              '重置密码确认',
              { type: 'warning' }
            )
            ElMessage.success('密码重置成功，新密码已发送至客户邮箱')
          } catch {
            ElMessage.info('已取消操作')
          }
          break
          
        case 'send-message':
          ElMessage.info(`向 ${customer.name} 发送消息`)
          break
          
        case 'toggle-status':
          const newStatus = customer.status === 'active' ? 'inactive' : 'active'
          customer.status = newStatus
          ElMessage.success(`客户状态已更新为: ${newStatus === 'active' ? '启用' : '禁用'}`)
          break
          
        case 'delete':
          handleDeleteCustomer(customer)
          break
      }
    }

    // 组件挂载时加载数据
    onMounted(() => {
      customers.value = mockCustomers
      ElMessage.success('客户数据加载完成')
    })

    return {
      customers,
      searchKeyword,
      statusFilter,
      dialogVisible,
      selectedCustomer,
      filteredCustomers,
      formatDate,
      handleSearch,
      handleStatusFilter,
      handleAddCustomer,
      handleViewCustomer,
      handleEditCustomer,
      handleDeleteCustomer,
      handleMoreActions
    }
  }
}
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.el-header {
  background-color: #fff;
  color: #333;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,.12), 0 0 6px rgba(0,0,0,.04);
  margin-bottom: 20px;
}

.el-header h1 {
  margin: 20px 0 10px 0;
  color: #409EFF;
}

.el-header p {
  margin: 0 0 20px 0;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.customer-list {
  min-height: 400px;
}

.danger-item {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .el-col {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-section .el-input {
    width: 100% !important;
  }
}
</style>